/**
 * Copyright © 1998-2020, Glodon Inc. All Rights Reserved.
 */
package reactor2.thread;

import reactor2.Event;

import reactor2.EventDispatcher;
import reactor2.EventType;
import reactor2.IEventHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 此处填写类简介
 * <p>
 * 此处填写类说明
 * </p>
 * 
 * @author glodon
 * @since jdk1.6 2020年8月3日
 */

/**
 * 此处填写类简介
 * <p>
 * 此处填写类说明
 * </p>
 * 
 * @author glodon
 * @since jdk1.6 2020年8月3日
 */
public abstract class AbstractEventRunnable<E> implements ISendRunnable<E> {

	protected ConcurrentLinkedQueue<E> msgQueue = new ConcurrentLinkedQueue<>();

	public static EventDispatcher eventDispatcher = new EventDispatcher();
	/****
	 * {@inheritDoc}
	 */
	private Executor executor = null;

	public AbstractEventRunnable(Executor executor) {

		this.executor = executor;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see ISendRunnable#addEvent(Object)
	 */
	@Override
	public boolean addEvent(E e) {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see ISendRunnable#cleanEvent()
	 */
	@Override
	public void cleanEvent() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean selector() {
		int msgQueueSize = msgQueue.size();
		/*
		 * if (msgQueueSize > 0) { for (int i = 0; i < msgQueueSize; i++) {
		 * Object obj = msgQueue.poll(); if (obj != null && obj instanceof
		 * Event) { Event event = (Event) obj; Map<EventType, IEventHandler> map
		 * = eventDispatcher.getEventHandlerMap(); IEventHandler handler =
		 * map.get(event.getEventType()); handler.handler(event); } } }
		 */
		return msgQueueSize > 0;
	}

	/***
	 * 
	 */
	public void runTask() {
		int msgQueueSize = msgQueue.size();
		if (msgQueueSize > 0) {
			for (int i = 0; i < msgQueueSize; i++) {
				Object obj = msgQueue.poll();
				if (obj != null && obj instanceof Event) {
					Event event = (Event) obj;
					Map<EventType, IEventHandler> map = eventDispatcher.getEventHandlerMap();
					IEventHandler handler = map.get(event.getEventType());
					handler.handler(event,executor);
				}
			}
		}
	}
}
